package uk.co.biggroup.lotto.syndicate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.client.ClientProtocolException;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.xml.sax.SAXException;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FirstLevel extends ListActivity {

	public static String[] names;
	public static String[] links;
	public static String[] luckynumbers;
	public static String balance;
	public static final String PREFS_NAME = "Settings";
	public static String token;
	public static int error;
	
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		error = 0;
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		String tokenCheck = settings.getString("token", "");
		
		if (tokenCheck.length() == 0) {
	        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	        intent.setPackage("com.google.zxing.client.android");
	        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	        startActivityForResult(intent, 0);
		}

		new DownloadGroups().execute("");
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
	    if (requestCode == 0) {
	        if (resultCode == RESULT_OK) {
	            String contents = intent.getStringExtra("SCAN_RESULT");
	    		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);	            
	    		SharedPreferences.Editor editor = settings.edit();
	    		editor.putString("token", contents);
	    		editor.commit();	    		
	        } else if (resultCode == RESULT_CANCELED) {
	            /**
	             * TODO Handle cancel
	             */
	        }
	    }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add("Refresh");
		return super.onCreateOptionsMenu(menu);
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		final Bundle bundle = new Bundle();
		bundle.putString("link", links[position]);
		bundle.putString("balance", balance);
		bundle.putString("luckynumbers", luckynumbers[position]);
		Logh.i("List item button pressed");
		Intent myIntents = new Intent(this, SecondLevel.class);
		myIntents.putExtras(bundle);
		startActivityForResult(myIntents, 0);
	}

	private class DownloadGroups extends AsyncTask<String, Void, String> {

		ProgressDialog dialog;

		@Override
		protected String doInBackground(String... params) {
			try {
				getHtml();
			} catch (ClientProtocolException e) {
				Logh.i("ClientProtocolException");
			} catch (IOException e) {
				Logh.i("IOException");
			} catch (XPatherException e) {
				Logh.i("XPatherException");
			} catch (ParserConfigurationException e) {
				Logh.i("ParserConfigurationException");
			} catch (SAXException e) {
				Logh.i("SAXException");
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();
			
			if (error == 1) {
		        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		        intent.setPackage("com.google.zxing.client.android");
		        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
		        startActivityForResult(intent, 0);
			}			
			
			FirstLevel.this
					.setListAdapter(new ArrayAdapter<String>(FirstLevel.this,
							R.layout.grouprowlayout, R.id.label, names));
		}

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(FirstLevel.this, "",
					"Wait, Accessing data...", true);
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		// /draws/draw
		public void getHtml() throws ClientProtocolException, IOException,
				XPatherException, ParserConfigurationException, SAXException,
				IOException, XPatherException {

			String AUDITIONS_XPATH = "//draws/draw/@date";
			String LINKS_XPATH = "//draws/draw/@id";
			String ID_XPATH = "//draws/draw/@status";
			String RESULT_XPATH = "//draws/draw/@result";
			String NUMBERS_XPATH = "//draws/draw[@id='6']/lines//line/@numbers";
			String BALANCE_XPATH = "//draws/@amount";
			String ERROR_XPATH = "//error/@msg";
			
			TagNode node;

			ArrayList<String> titlesList = new ArrayList<String>();
			ArrayList<String> linksList = new ArrayList<String>();
			ArrayList<String> idsList = new ArrayList<String>();
			ArrayList<String> resultsList = new ArrayList<String>();
			ArrayList<String> numbersList = new ArrayList<String>();
			ArrayList<String> balanceList = new ArrayList<String>();
			ArrayList<String> errorList = new ArrayList<String>();

			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			String tokenCheck = settings.getString("token", "");
			
			URL url = new URL(
					"http://syndicates.biggroup.co.uk/MyAccount/DownloadXML.aspx?t=" + tokenCheck);
			URLConnection conn = url.openConnection();

			HtmlCleaner cleaner = new HtmlCleaner();
			CleanerProperties props = cleaner.getProperties();
			props.setAllowHtmlInsideAttributes(true);
			props.setAllowMultiWordAttributes(true);
			props.setRecognizeUnicodeChars(true);
			props.setTranslateSpecialEntities(true);
			props.setOmitComments(true);

			node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
			Object[] info_nodes = node.evaluateXPath(AUDITIONS_XPATH);
			Object[] links_nodes = node.evaluateXPath(LINKS_XPATH);
			Object[] ids_nodes = node.evaluateXPath(ID_XPATH);
			Object[] results_nodes = node.evaluateXPath(RESULT_XPATH);
			Object[] numbers_nodes = node.evaluateXPath(NUMBERS_XPATH);
			Object[] balance_nodes = node.evaluateXPath(BALANCE_XPATH);
			Object[] error_nodes = node.evaluateXPath(ERROR_XPATH);

			if (error_nodes.length > 0) {
				for (Object linkNode : error_nodes) {
					String s = linkNode.toString();
					errorList.add(s);
					error = 1;
					Logh.i(s);
				}
			}
			
			if (balance_nodes.length > 0) {
				for (Object linkNode : balance_nodes) {
					String s = linkNode.toString();
					balance = s;
					balanceList.add(s);
					Logh.i(s);
				}
			}

			if (numbers_nodes.length > 0) {
				for (Object linkNode : numbers_nodes) {
					String s = linkNode.toString();
					numbersList.add(s);
					Logh.i(s);
				}
			}

			if (info_nodes.length > 0) {
				for (Object linkNode : info_nodes) {
					String s = linkNode.toString();
					titlesList.add(s);
					Logh.i(s);
				}

			}

			if (links_nodes.length > 0) {
				for (Object linksNode : links_nodes) {
					String s = linksNode.toString();
					linksList.add(s);
					Logh.i(s);
				}
			}

			if (ids_nodes.length > 0) {
				for (Object idsNode : ids_nodes) {
					String s = idsNode.toString();
					idsList.add(s);
					Logh.i(s);
				}
			}

			if (results_nodes.length > 0) {
				for (Object resNode : results_nodes) {
					String s = resNode.toString();
					resultsList.add(s);
					Logh.i(s);
				}
			}

			int itemCount = titlesList.size();
			names = new String[itemCount];
			links = new String[itemCount];
			luckynumbers = new String[itemCount];
			Logh.i(Integer.toString(itemCount));
			for (int i = 0; i < itemCount; i++) {
				names[i] = titlesList.get(i) + " " + idsList.get(i);
				links[i] = linksList.get(i);
				luckynumbers[i] = resultsList.get(i);
				Logh.i(Integer.toString(i + 1));
			}

		}
	}
}